﻿
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using MX.Core.Caching.Redis.Sider.Executors;


namespace MX.Core.Caching.Redis.Sider
{
	public abstract class RedisClientBase
	{
		 
		private ProtocolReader _reader = new ProtocolReader ();
		 
		private ProtocolWriter _writer = new ProtocolWriter ();

		private IExecutor _executor;

		private bool _disposing;
		private bool _disposed;


		public bool IsDisposed { get { return _disposed; } }

		protected bool IsDisposing { get { return _disposing; } }

		internal IExecutor Executor { get { return _executor; } }

		// expose reader and writer to IExecutors
		internal ProtocolReader Reader { get { return _reader; } }

		internal ProtocolWriter Writer { get { return _writer; } }

		protected RedisClientBase(){
			_executor = new ImmediateExecutor();
			_executor.Init(this);
		}

		 
		 

		internal T SwitchExecutor<T> (T newExecutor)
      where T : IExecutor
		{
			newExecutor.Init (previous: _executor);
			_executor.Dispose (); // after INIT to make sure the new executor works

			_executor = newExecutor;
			return newExecutor;
		}


		public virtual void Dispose ()
		{
			if (_disposing || _disposed)
				return;
			_executor.Dispose ();
			_disposing = true;
			_disposed = true;
		}
	}
}
